<template>
  <div class="xunfei-chat-container">
    <el-card class="chat-card">
      <template #header>
        <div class="chat-header">
          <h2>讯飞智能助手</h2>
          <div class="connection-status">
            <el-tag :type="connectionStatus === 'Connected' ? 'success' : 'danger'">
              {{ connectionStatus }}
            </el-tag>
          </div>
        </div>
      </template>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', message.type]"
        >
          <div class="message-avatar">
            <el-avatar :size="40">
              <span>{{ message.type === 'user' ? '我' : 'AI' }}</span>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="message-item ai">
          <div class="message-avatar">
            <el-avatar :size="40">
              <span>AI</span>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题..."
          @keydown.ctrl.enter="sendMessage"
          :disabled="isLoading"
        />
        <div class="input-actions">
          <el-button
            type="primary"
            @click="sendMessage"
            :loading="isLoading"
            :disabled="!inputMessage.trim()"
          >
            发送 (Ctrl+Enter)
          </el-button>
          <el-button @click="clearMessages">清空对话</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { sendChatMessage, checkXunfeiHealth } from './xunfeiApi'

// 本地消息接口（独立定义）
interface LocalChatMessage {
  type: 'user' | 'ai'
  content: string
  timestamp: Date
}

// 响应式数据
const messages = ref<LocalChatMessage[]>([])
const inputMessage = ref('')
const isLoading = ref(false)
const connectionStatus = ref<'Connected' | 'Disconnected' | 'Connecting'>('Disconnected')
const messagesContainer = ref<HTMLElement>()

// 格式化时间
const formatTime = (date: Date): string => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage: LocalChatMessage = {
    type: 'user',
    content: inputMessage.value.trim(),
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const currentInput = inputMessage.value.trim()
  inputMessage.value = ''
  isLoading.value = true

  try {
    await scrollToBottom()
    
    // 直接发送消息到后台MCP接口
    const response = await sendChatMessage(currentInput)

    // 处理MCP接口响应
    let aiContent = ''
    if (response.code === 200) {
      // 如果响应成功，使用data中的内容
      aiContent = response.data?.content || response.data?.message || response.message || '收到回复'
    } else {
      // 如果响应失败，显示错误信息
      aiContent = response.message || '抱歉，我无法理解您的问题。'
    }

    const aiMessage: LocalChatMessage = {
      type: 'ai',
      content: aiContent,
      timestamp: new Date()
    }

    messages.value.push(aiMessage)
    
  } catch (error: any) {
    console.error('发送消息失败:', error)
    
    const errorMessage: LocalChatMessage = {
      type: 'ai',
      content: `抱歉，发生了错误：${error?.message || '网络连接失败'}`,
      timestamp: new Date()
    }
    
    messages.value.push(errorMessage)
    ElMessage.error('发送消息失败，请检查网络连接')
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

// 清空对话
const clearMessages = () => {
  messages.value = []
  ElMessage.success('对话已清空')
}

// 检查连接状态
const checkConnection = async () => {
  try {
    connectionStatus.value = 'Connecting'
    await checkXunfeiHealth()
    connectionStatus.value = 'Connected'
  } catch (error) {
    connectionStatus.value = 'Disconnected'
    console.error('连接检查失败:', error)
  }
}

// 初始化欢迎消息
const initWelcomeMessage = () => {
  const welcomeMessage: LocalChatMessage = {
    type: 'ai',
    content: '您好！我是讯飞智能助手，有什么可以帮助您的吗？',
    timestamp: new Date()
  }
  messages.value.push(welcomeMessage)
}

// 生命周期
onMounted(() => {
  checkConnection()
  initWelcomeMessage()
})

// 自动滚动到底部
watch(messages, async () => {
  await scrollToBottom()
}, { deep: true })
</script>

<style scoped>
.xunfei-chat-container {
  height: 100vh;
  padding: 20px;
  background: #f5f5f5;
}

.chat-card {
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  color: #409eff;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  max-height: calc(100vh - 200px);
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 12px;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  background: #fff;
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.message-item.user .message-bubble {
  background: #409eff;
  color: white;
}

.message-text {
  margin-bottom: 4px;
  line-height: 1.5;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  text-align: right;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #409eff;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input {
  border-top: 1px solid #e4e7ed;
  padding-top: 20px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
